//
//  QRCodePhotoViewController.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/16.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit

class QRCodePhotoViewController: UIViewController {

    @IBOutlet weak var qrCodeImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "我的名片"
        //创建二维码滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        //初始化滤镜
        filter?.setDefaults()
        //设置滤镜内容
        filter?.setValue("hello".data(using: String.Encoding.utf8), forKeyPath: "InputMessage")
        //滤镜输出内容
        guard let ciImage = filter?.outputImage else{
            return
        }
        
        qrCodeImageView.image = createNonInterpolatedUIImageFormCIImage(image: ciImage, size: 1000)
    }
    
    
    /**
     生成高清二维码
     
     - parameter image: 需要生成原始图片
     - parameter size:  生成的二维码的宽高
     */
    private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage? {

        
        let extent: CGRect = image.extent.integral
        let scale: CGFloat = min(size/extent.width, size/extent.height)
        
        // 1.创建bitmap;
        let width = extent.width * scale
        let height = extent.height * scale
        let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
        
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0)!

        let context = CIContext(options: nil)
        guard let bitmapImage: CGImage = context.createCGImage(image, from: extent) else{
            return nil
        }
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: scale, y: scale)
        bitmapRef.draw(bitmapImage, in: extent)

        // 2.保存bitmap到图片
        guard let scaledImage: CGImage = bitmapRef.makeImage() else{
            return nil
        }
        
        return UIImage(cgImage: scaledImage)
    }

}
